// 我的简历
const app = getApp();
Page({

    data: {
        name: '',
        studentNumber: '',
        department: '',
        grade: '',
        major: '',
        qq: '',
        resume: '',
        school: '',
        telephone: '',

        attachment: '',
        nickname: '',
        portrait: '',
        wechatNum: '',

        modalFlag: false,
        sessionID: '',
        chuangNum: '',
        prolist:[],
        str:"",
        showPrivacy:false,

    },

    onLoad() {
        this.setData({
            userInfo: wx.getStorageSync('userInfo'), // 用户的微信头像、昵称等信息
            loginFlag: wx.getStorageSync('loginFlag'), // 判断是否登录，登录为1，未登录为0或空
            sessionID: wx.getStorageSync('sessionID'),
            chuangNum: wx.getStorageSync('chuangNum'),
          })
        if (this.data.loginFlag != 1) {
            this.myShowModal();
        }
        // console.log("chuangNum", wx.getStorageSync('chuangNum'));
        // console.log("this.data", this.data);
        wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
            console.log('触发本次事件的接口是：' + eventInfo.referrer)
            // 需要用户同意隐私授权时
            // 弹出开发者自定义的隐私授权弹窗
            this.setData({
              showPrivacy: true
            })
            this.resolvePrivacyAuthorization = resolve
          })
        // 获取后端数据，显示个人信息

        wx.request({
            url: 'https://www.hschuangsai.com/user/experience?userChuangNum=' + this.data.chuangNum,
            method: 'GET',
            header: {
                'session': this.data.sessionID
            },
            success: (res) => {
                console.log(res.data)
                if (res.statusCode!=200){
                    wx.showToast({
                        title: '获取项目列表失败',
                        icon: 'none',
                        duration: 800     
                      })  
                }
                this.setData({
                    prolist:res.data.data
                })
            }
        });
        wx.request({
            url: 'https://www.hschuangsai.com/user/info?userChuangNum=' + this.data.chuangNum,
            method: 'GET',
            header: {
                'session': this.data.sessionID
            },
            success: (res) => {
                if (res.statusCode!=200){
                    wx.showToast({
                        title: '获取用户信息失败',
                        icon: 'none',
                        duration: 800     
                      })  
                }
                // console.log("user/info success", res);
                this.requestSetData(res.data.data);
            }
        });
    },
    openDocument1:function(e){
        let suffix='';
        const fileArr=this.data.attachment.split('.');
        suffix=fileArr[fileArr.length-1];
        wx.downloadFile({
            url: this.data.attachment,
            filePath: wx.env.USER_DATA_PATH + '/' + this.data.attachmentName,
            success: function (res) {
                console.log(res)
                if (res.statusCode == 200) {
                    let filePath = res.filePath
                    wx.openDocument({
                        fileType: suffix,
                        filePath: filePath
                    })
                }
                else{
                    wx.showToast({
                        title: '打开文件失败',
                        icon: 'none',
                        duration: 800     
                      })  
                }
            }
        })
    },
    openDocument2:function(e){
        let suffix='';
        const fileArr=this.data.attachment3.split('.');
        suffix=fileArr[fileArr.length-1];
        wx.downloadFile({
            url: this.data.attachment2,
            filePath: wx.env.USER_DATA_PATH + '/' + this.data.attachment2Name,
            success: function (res) {
                console.log(res)
                if (res.statusCode == 200) {
                    let filePath = res.filePath
                    wx.openDocument({
                        fileType: suffix,
                        filePath: filePath
                    })
                }
                else{
                    wx.showToast({
                        title: '打开文件失败',
                        icon: 'none',
                        duration: 800     
                      })  
                }
            }
        })
    },
    

    openDocument3:function(e){
        let suffix='';
        const fileArr=this.data.attachment3.split('.');
        suffix=fileArr[fileArr.length-1];
        wx.downloadFile({
            url: this.data.attachment3,
            filePath: wx.env.USER_DATA_PATH + '/' + this.data.attachment3Name,
            success: function (res) {
                console.log(res)
                if (res.statusCode == 200) {
                    let filePath = res.filePath
                    wx.openDocument({
                        fileType: suffix,
                        filePath: filePath
                    })
                }
                else{
                    wx.showToast({
                        title: '打开文件失败',
                        icon: 'none',
                        duration: 800     
                      })  
                }
            }
        })
    },

    onShow(e){
        // this.setData({
        //      html:JSON.parse(wx.getStorageSync('DescriptHtml'))
        // })
        // console.log("html is",this.data.html)
        // var WxParse = require('../../wxParse/wxParse.js');
        // var data=this.data;
        // WxParse.wxParse('content', 'html', data.html, this, 10);
        this.setData({
            modalFlag: false
        })
        wx.request({
            url: 'https://www.hschuangsai.com/user/info?userChuangNum=' + this.data.chuangNum,
            method: 'GET',
            header: {
                'session': this.data.sessionID
            },
            success: (res) => {
                if (res.statusCode!=200){
                    wx.showToast({
                        title: '获取用户信息失败',
                        icon: 'none',
                        duration: 800     
                      })  
                }

                console.log("user/info success", res);
                this.requestSetData(res.data.data);

                if (this.data.name === '' || this.data.school === '' || this.data.studentNumber === '') {
                    this.setData({
                        modalFlag: true
                    })
                }
                if (this.data.resume!=this.data.html)
                {
                    let data = this.data;
                    wx.request({
                        url: 'https://www.hschuangsai.com/user/fill',
                        method: 'POST',
                        data: {
                            attachment: data.attachment,
                            department: data.department,
                            gender: 0,
                            grade: data.grade,
                            major: data.major,
                            name: data.name,
                            nickname: data.nickname,
                            portrait: data.portrait,
                            qq: data.qq,
                            resume: data.resume,
                            school: data.school,
                            studentNumber: data.studentNumber,
                            telephone: data.telephone,
                            wechatNum: data.wechatNum
                        },
                        header: {
                            'session': this.data.sessionID
                        },
                        success: (res) => {
                            if (res.statusCode!=200) {
                                wx.showToast({
                                    title: '保存失败，请重试',
                                    icon: 'none',
                                    duration: 800     
                                  })  
                            }
                            if (this.data.name != '' && this.data.school != '' && this.data.studentNumber != '') {
                                this.setData({
                                    modalFlag: false
                                })
                            }
                        }
                    });
                }
            }
        });
    },

    requestSetData(data) {
        console.log(data)
        this.setData({
            name: data.name,
            studentNumber: data.studentNumber,
            department: data.department,
            grade: data.grade,
            major: data.major,
            qq: data.qQ,
            resume:data.resume,
            school: data.school,
            telephone: data.telephone,
            attachment: data.attachment,
            nickname: data.nickname,
            portrait: data.portrait,
            wechatNum: data.wechatNum,
            attachment:data.attachment,
            attachmentName:decodeURI(data.attachmentName),
            attachment2:data.attachment2,
            attachment2Name:decodeURI(data.attachment2Name),
            attachment3:data.attachment3,
            attachment3Name:decodeURI(data.attachment3Name),
        })
        this.setData({
            str:wx.getStorageSync('DescriptHtml')
       })
        console.log("str",this.data.str)
        if(this.data.str==""&&this.data.resume!="")
        {
            console.log("resume load")
            var strr=JSON.stringify(this.data.resume)
            wx.setStorageSync('DescriptHtml',strr)
        }
        

        if (data.name === '' || data.school === '' || data.studentNumber === '') {
            this.setData({
                modalFlag: true
            })
        }
    },

    nameChange(e) {
        this.setData({
            name: e.detail.value
        })
    },

    schoolChange(e) {
        this.setData({
            school: e.detail.value
        })
    },

    studentNumChange(e) {
        this.setData({
            studentNumber: e.detail.value
        })
    },

    submit(e) {
        let data = this.data;
        if (data.name != '' && data.school != '' && data.studentNumber != '') {
            this.showModal();
        }
        else {
            wx.showToast({
                title: '请填写完整',
                icon: 'none',
                duration: 800     
              })  
        }
    },

    cancel() {
        wx.switchTab({
            url: '../account'
        })
    },

    showModal() {
        wx.showModal({
            title: '提示',
            content: '该信息填写后无法修改，确定要提交吗？',
            success :(res) => {
                if (res.confirm) {
                    this.autoSave();
                }
            }
        })
    },

    teleChange(e) {
        this.setData({
            telephone: e.detail.value
        })
    },

    departChange(e) {
        this.setData({
            department: e.detail.value
        })
    },

    majorChange(e) {
        this.setData({
            major: e.detail.value
        })
    },

    gradeChange(e) {
        this.setData({
            grade: e.detail.value
        })
    },

    qqChange(e) {
        this.setData({
            qq: e.detail.value
        })
    },

    resumeChange(e) {
        this.setData({
            resume: e.detail.value
        })
    },

    autoSave() {
        let data = this.data;
        wx.request({
            url: 'https://www.hschuangsai.com/user/fill',
            method: 'POST',
            data: {
                attachment: data.attachment,
                department: data.department,
                gender: 0,
                grade: data.grade,
                major: data.major,
                name: data.name,
                nickname: data.nickname,
                portrait: data.portrait,
                qq: data.qq,
                resume: data.resume,
                school: data.school,
                studentNumber: data.studentNumber,
                telephone: data.telephone,
                wechatNum: data.wechatNum
            },
            header: {
                'session': this.data.sessionID
            },
            success: (res) => {
                if (res.statusCode!=200) {
                    wx.showToast({
                        title: '保存失败，请重试',
                        icon: 'none',
                        duration: 800     
                      })  
                }
                if (this.data.name != '' && this.data.school != '' && this.data.studentNumber != '') {
                    this.setData({
                        modalFlag: false
                    })
                }
            }
        });
    },

    myShowModal() {
        wx.showModal({
            title: '提示',
            content: '登录后查看更多，是否登录？',
            success: (res) => {
                // 确定
                if (res.confirm) {
                    this.logIn();
                }
                else {
                     wx.showToast({
                         title: '跳转到首页',
                         icon: 'none',
                        duration: 1500
                     })
                     setTimeout(function () {
                      wx.switchTab({
                        url: '/pages/recruit/recruit',
                        success:function(e)
                        {
                          var page = getCurrentPages().pop();
                          if (page == undefined || page == null) return;
                          page.onLoad();
                        }
                      })  
                    }, 1500)
                }
            }
        })
      },
    
      logIn() {
        // 如果userInfo为空，则未确认过微信授权弹窗，即首次登录
        if (!this.data.userInfo) {
            // 微信授权弹窗
            wx.getUserProfile({
                desc: '用于获取用户头像和昵称',
                // 用户点击确认
                success: (res) => {
                    let userInfo = res.userInfo;
                    wx.setStorageSync('userInfo', userInfo); // 缓存userInfo
                    this.myLogin(); // 进行登录
                },
                // 用户点击取消
                fail: (res) => {
                    // wx.showToast({
                    //     title: '跳转到首页',
                    //     icon: 'none',
                    //     duration: 1500
                    // })
                }
            })
        }
        // 非首次登录
        else {
            this.myLogin(); // 重新登录
        }
    },
    
    // wx.login()封装
    myLogin() {
        wx.login({
            success: (res) => {
                wx.request({
                    url: 'https://www.hschuangsai.com/user/login/' + res.code,
                    method: 'GET',
                    success: (res) => {
                        console.log("myLogin success", res);
                        let sessionID = res.data.data.sessionId;
                        wx.setStorageSync('chuangNum',res.data.data.chuangNum)
                        wx.setStorageSync('sessionID', sessionID); // 缓存sessionID
                        wx.setStorageSync('loginFlag', 1); // 缓存loginFlag
                        this.setData({
                            sessionID: sessionID,
                            loginFlag: 1,
                        });
    
                        wx.showToast({
                            title: '成功登录，继续创建队伍',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            }
        })
    },
    handleAgreePrivacyAuthorization() {
        // 用户点击同意按钮后
        this.resolvePrivacyAuthorization({ buttonId: 'agree-btn', event: 'agree' })
        // 用户点击同意后，开发者调用 resolve({ buttonId: 'agree-btn', event: 'agree' })  告知平台用户已经同意，参数传同意按钮的id。为确保用户有同意的操作，基础库在 resolve 被调用后，会去检查对应的同意按钮有没有被点击过。检查通过后，相关隐私接口会继续调用
        // 用户点击拒绝后，开发者调用 resolve({ event:'disagree' }) 告知平台用户已经拒绝
      },
    uploadAttachment(e){
        var that=this;
        wx.chooseMessageFile({
            　　count:1,        //上传的文件数目
            　　type:'file',　　//上传类型，一共三种，可以去微信小程序API看
            　　success(res){
            　　　　var tempFilePaths = res.tempFiles[0];  //tempFiles对象中，对返回你上传文件基本信息，name文件名，size文件大小，单位是B，path微信提供的临时存放路径，我们需要这个
            　　　　that.setData({
            　　　　　　fileName:tempFilePaths.name,
            　　　　})
            console.log(encodeURI(res.tempFiles[0].name))
            wx.uploadFile({
                　　　　　　url: 'https://www.hschuangsai.com/user/resumeUpload',   //将上传请求发到后台处理
                　　　　　　filePath: res.tempFiles[0].path,
                　　　　　　name: 'file',   //这个属性比较重要，这个属性值与spring中的全局变量名一致，spring会自动装配，将附件信息存到后台的file对象中。非常方便
                           method: 'POST',
                　　　　　　formData:{
                　　　　　　　　fileData: encodeURI(res.tempFiles[0].name)
                　　　　　　},
                　　　　　　header: {
                　　　　　　　　"Content-Type": "multipart/form-data; boundary=----WebKitFormBoundarym9rNf7EsEiv7jdhu",
                               'session': that.data.sessionID
                　　　　　　　},
                　　　　　　success:function(res){
                    if (res.statusCode!=200) {
                        wx.showToast({
                            title: '上传附件失败，请重试',
                            icon: 'none',
                            duration: 800     
                          })  
                    }
                　　　　　　},
                        
                　　　　})
            　　}
            });
    }
})
